package org.skydiveapp2;

import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapplibrary.data.Aircraft;
import org.skydiveapplibrary.repository.AircraftRepository;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class AircraftEditActivity extends Activity
{
	// requests
    private static final int REQUEST_NOTES = 0;
    
	// repository
	private AircraftRepository repository = new AircraftRepository(this);
	
	// data
	private boolean isEdit = false;
	private Aircraft aircraft;
	
	// listeners
	private OnClickListener notesEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			Intent intent = new Intent(AircraftEditActivity.this, NotesEditActivity.class);
            intent.putExtra(Constants.EXTRA_NOTES, aircraft.getNotes());
            startActivityForResult(intent, REQUEST_NOTES);
		}
	};
	private DialogInterface.OnClickListener deleteConfirmListener = new DialogInterface.OnClickListener()
	{
		@Override
		public void onClick(DialogInterface arg0, int arg1)
		{
			delete();
		}
	};
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
    	
		overridePendingTransition(R.anim.fadein,
                R.anim.hold);
		
		setContentView(R.layout.aircraft_edit_view);
		
		// load data
		loadData();
		
		initializeUI();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
            if (requestCode == REQUEST_NOTES && resultCode == RESULT_OK)
            {
                    String notes = intent.getStringExtra(Constants.EXTRA_NOTES);
                    updateNotes(notes);
            }
    }
	
	private void loadData()
	{
		// set isEdit flag
        Bundle extras = getIntent().getExtras();
        isEdit = (extras != null && extras.containsKey(Constants.EXTRA_AIRCRAFT_ID));

        // determine add vs. edit
        if (isEdit)
        {
                // editing
                int id = getIntent().getExtras().getInt(Constants.EXTRA_AIRCRAFT_ID);
                aircraft = repository.getAircraft(id);
        }
        else
        {
                // adding
                aircraft = new Aircraft();
        }
	}
	
	private void initializeUI()
	{
		if (this.findViewById(R.id.tabletLayout) != null)
		{
			InterfaceManager.getInstance().configureTabletUI(this, 
					isEdit ? R.string.aircraft_edit_label : R.string.aircraft_new_label);
		}
		else
		{
			InterfaceManager.getInstance().configurePhoneUI(this, 
					isEdit ? R.string.aircraft_edit_label : R.string.aircraft_new_label);
		}
		
		// set name
		EditText nField = (EditText) findViewById(R.id.AircraftNameField);
		nField.setText(aircraft.getName());
		
		// set notes
		TextView notesField = (TextView) findViewById(R.id.AircraftNotesField);
		notesField.setText(aircraft.getNotes());
		notesField.setOnClickListener(notesEditListener);
	}
	
	private void showDeleteWarning()
	{
		// create alert dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(
				new ContextThemeWrapper(this, android.R.style.Theme_Holo_Dialog));
		builder.setMessage(R.string.aircraft_delete_warning);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.delete_confirmation);
		builder.setPositiveButton(R.string.yes_button, deleteConfirmListener);
		builder.setNegativeButton(R.string.no_button, null);
		AlertDialog dialog = builder.create();
		// show dialog
		dialog.show();
	}
	
	public void updateNotes(String notes)
	{
		// update aircraft
		aircraft.setNotes(notes);
	}

	private void commitChanges()
	{
		// set name
		EditText nField = (EditText) findViewById(R.id.AircraftNameField);
		String name = nField.getText().toString();
		aircraft.setName(name);
	}
	
	private void save()
	{
		commitChanges();
		
		// save
		if (isEdit)
		{
			repository.updateAircraft(aircraft);
		}
		else
		{
			repository.addAircraft(aircraft);
		}
		
		// finish
		getFragmentManager().popBackStack();
	}
	
	private void delete()
	{
		// delete aircraft
		repository.deleteAircraft(aircraft);
		
		// finish
		getFragmentManager().popBackStack();
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu_save, menu);
    	
        if (isEdit)
        	inflater.inflate(R.menu.menu_delete, menu);
        
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menu_save:
    		save();
            return true;
            
        case R.id.menu_back:
			close();
            return true;
            
        case R.id.menu_delete:
        	showDeleteWarning();
            return true;
            
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
    	overridePendingTransition(R.anim.hold,
                R.anim.fadeout);
	}
}